package com.lihan.GetSeatInLib.Service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.lihan.GetSeatInLib.Domain.LibTable;
import com.lihan.GetSeatInLib.Domain.Enums.TableStatus;
import com.lihan.GetSeatInLib.Exceptions.SeatNumOverException;
import com.lihan.GetSeatInLib.Repository.LibTableRepository;
import com.lihan.GetSeatInLib.Service.LibTableService;

@Service
public class LibTableServiceImpl  implements LibTableService{
	
	@Autowired
	private LibTableRepository _tabledao;

	@Autowired
	@Qualifier("redisTemplate")
	private RedisTemplate<String, LibTable> redis;
	
	
	@Override
	public Set<LibTable> getAllLibTale() {
		List<LibTable> findAll = _tabledao.findAll(Sort.by("ID"));
		HashSet<LibTable> hashSet = new HashSet<LibTable>();
		findAll.forEach((item)->{
			hashSet.add(item);
		});
		return hashSet;
	}
	
	
	@Override
	public LibTable getTibTableById(Long id) {
		return _tabledao.getById(id);
	}
	@Override
	public LibTable getTibTableByTableIndex(String TableIndex) {
		return _tabledao.getTibTableByIndexName(TableIndex);
	}

	//这里加一个判断是否保存的座位个数超出
	@Override
	public boolean UpdateLibTable(LibTable table) throws SeatNumOverException {
		
		if(table.getSeat_Number()<table.getSeatlist().size())
			throw new SeatNumOverException();
		_tabledao.save(table);
		return true;
	}

	@Override
	public boolean DeleteTableById(Long id) {
		try {
			_tabledao.deleteById(id);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	@Override
	public boolean CreateNewTable(LibTable table) {
		if(_tabledao.save(table)!=null)
			return true;
		else
			return false;	
	}
	
	//锁定桌子
	@Override
	public boolean LockSeat(Long ID) {
		LibTable table = _tabledao.getById(ID);
		if(table.getStatus()==TableStatus.FREE) {
			table.setStatus(TableStatus.LOCKED);
			_tabledao.save(table);
			return true;
		}
		return false;
	}
	
	//解锁桌子
	@Override
	public boolean UnLockSeat(Long ID) {
		LibTable table = _tabledao.getById(ID);
		if(table.getStatus()==TableStatus.LOCKED) {
			table.setStatus(TableStatus.FREE);
			_tabledao.save(table);
			return true;
		}
		return false;
	}

}
